#include <SDL/SDL_image.h>
#include "Sprite.h"

using namespace SDL::UTILS;

Sprite::Sprite()
	: Name(""), CurrentFrame(), m_lastCount(0), m_count(0), m_delay(0)
{
}

Sprite::Sprite(std::string const& _name, SDL_Surface* _surface, Rect const& _frameSize, Uint16 _delay)
	: Name(_name), CurrentFrame(0, 0, _frameSize.GetW(), _frameSize.GetH()), m_lastCount(0), m_count(0), m_delay(_delay)
{
	Src.SetSurface(_surface);
	Src.SetDontFree(true);
	Src.SetColorKey(0xFF00FF);
}

Sprite::Sprite(Sprite const& _sprite)
{
	*this = _sprite;
}

Sprite::~Sprite()
{
}

Sprite& Sprite::operator=(Sprite const& _sprite)
{
	if (this != &_sprite)
	{
		Src.SetDontFree(_sprite.Src.GetDontFree());
		Src.SetSurface((*((Sprite*)&_sprite)).Src.GetSurface());
		Name = _sprite.Name;
		CurrentFrame = _sprite.CurrentFrame;
		m_lastCount = 0;
		m_count = 0;
		m_delay = _sprite.m_delay;
		m_finish = false;
	}
	return (*this);
}

void Sprite::ResetFrame()
{
	CurrentFrame = Rect(0, 0, CurrentFrame.GetW(), CurrentFrame.GetH());
	m_finish = false;
}

bool Sprite::SelectNextFrame()
{
	SDL_Surface* s = Src.GetSurface();
	if (s == NULL)
		return (false);

	Uint16 w = CurrentFrame.GetW(), h = CurrentFrame.GetH();
	Sint16 x = CurrentFrame.GetX(), y = CurrentFrame.GetY();

	if (x + w >= s->w)
	{
		if (y + h >= s->h)
		{
			CurrentFrame.SetX(0);
			CurrentFrame.SetY(0);
			m_finish = true;
			return (true);
		}
		else
		{
			CurrentFrame.SetX(0);
			CurrentFrame.SetY(y + h);
		}
	}
	else
		CurrentFrame.SetX(x + w);
	m_finish = false;
	return (false);
}

bool Sprite::Animate()
{
	m_count = SDL_GetTicks();
	if (m_count - m_lastCount > m_delay)
	{
		m_lastCount = m_count;
		return (this->SelectNextFrame());
	}
	return (false);
}

bool Sprite::Finish() const
{
	return (m_finish);
}
